/**
 * Adapter danh sach cac bai hat Online
 */
package com.toidep.adapters;

import java.util.ArrayList;

import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.toidep.R;
import com.toidep.api.ApiController;
import com.toidep.api.ParseJSON;
import com.toidep.base.BaseFragment;
import com.toidep.config.ConfigUtility;
import com.toidep.entities.EmailEntity;
import com.toidep.interfaces.ResponseListener;
import com.toidep.utilities.DialogUtility;
import com.toidep.widgets.sectionlist.AmazingAdapter;

public class EmailAdapter extends AmazingAdapter {
	
	private BaseFragment parentFragment;
	
	private ArrayList<EmailEntity> listEmails;

	/**
	 * Constructor  
	 * Khoi tao Adapter lay danh sach Comment
	 * @param ff
	 * @param adapterTypeByScreen
	 * @param typeComment = 1: Model | 2: Album | 3: Video 
	 * @param parent_id
	 */
	public EmailAdapter(BaseFragment ff) {
		this.parentFragment = ff;
		this.listEmails = new ArrayList<EmailEntity>();
	}
	
	public ArrayList<EmailEntity> getListAdapter() {
		return this.listEmails;
	}
	
	public int getCount() {
		if (listEmails != null)
			return listEmails.size();
		else 
			return 0;
	}

	public EmailEntity getItem(int position) {
		return listEmails.get(position);
	}

	public long getItemId(int position) {
		return position;
	}
	
	// TODO: onNextPageRequested
	@Override
	protected void onNextPageRequested(int page) {
		getListData(page);
	}

	@Override
	protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
		// do nothing
	}

	@Override
	public void configurePinnedHeader(View header, int position, int alpha) {
		
	}

	@Override
	public int getPositionForSection(int section) {
		return 0;
	}

	@Override
	public int getSectionForPosition(int position) {
		return 0;
	}

	@Override
	public int getSectionPosition(int position) {
		return 0;
	}

	@Override
	public Object[] getSections() {
		return null;
	}
	
	/**
	 * Clear Adapter ve null
	 */
	public void clear() {
		resetPage();
		listEmails.clear();
		clearTemporarity();
		notifyDataSetChanged();
	}
	
	/**
	 * Xoa cac bien su dung: ViewHolder...
	 */
	public void clearTemporarity() {
//		if (arrViewHolder != null)
//			arrViewHolder.clear();
//		arrViewHolder = null;
	}
	
	/**
	 * Clear memory cache
	 */
	public void clearMemoryCacheOnly() {
		Log.e("SongsAdapter", "clearMemoryCacheOnly");
//		imageFetcher.clearMemoryCacheOnly();
	}
	
	/**
	 * Goi ham nay khi Fragment chua no xay ra onDestroy
	 */
	public void destroyAdapter() {
		clear();
		listEmails = null;
//		imageFetcher = null;
	}
	
	private class ViewHolder {
		public TextView textEmail, textSubject, textCreated;
	}

	@Override
	public View getAmazingView(int position, View convertView, ViewGroup parent) {
		final ViewHolder viewHolder;
		if (convertView == null) {
			
			convertView = parentFragment.getActivity().getLayoutInflater().inflate(R.layout.layout_itemlist_email, null);
			viewHolder = new ViewHolder();
			
			viewHolder.textEmail = (TextView) convertView.findViewById(R.id.textEmail);
			viewHolder.textSubject = (TextView) convertView.findViewById(R.id.textSubject);
			viewHolder.textCreated = (TextView) convertView.findViewById(R.id.textCreated);
			
			convertView.setTag(viewHolder);
			
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		
		final EmailEntity currentItem = getItem(position);
		
		viewHolder.textEmail.setText(currentItem.getTo_email());
		viewHolder.textSubject.setText(currentItem.getSubject());
		viewHolder.textCreated.setText(currentItem.getCreated());
		
		return convertView;
	}
	
	public void resetList() {
		if (listEmails == null) {
			listEmails = new ArrayList<EmailEntity>();
		}
		listEmails.clear();
		
		getFirstPage();
	}
	
	public void resetList(ArrayList<EmailEntity> l) {
		if (listEmails == null) {
			listEmails = new ArrayList<EmailEntity>();
		}
		listEmails.clear();
		listEmails.addAll(l);
		
		notifyDataSetChanged();
	}

	private void requestAPI(int page, ResponseListener responseListener) {
		ApiController.getEmails(parentFragment.getActivity(), page, ConfigUtility.PAGE_SIZE, responseListener);
	}
	
	private void getListData(final int page) {
		
		ResponseListener responseListener = new ResponseListener() {
			
			@Override
			public void processResponse(int inintstall) {
				notifyNoMorePages();
			}
			
			@Override
			public void processResponse(String response) {
				if (response != null) {
					try {
						ArrayList<EmailEntity> list = ParseJSON.getAllEmailsFromResponse(response);
						if (list != null && list.isEmpty() == false) {
							listEmails.addAll(list);
							nextPage();
							notifyDataSetChanged();
							if (list.size() < ConfigUtility.PAGE_SIZE)
								notifyNoMorePages();
							else
								notifyMayHaveMorePages();
						} else {
							notifyNoMorePages();
						}
					} catch (Exception e) {
						notifyNoMorePages();
					} finally {
						isLoadingMore = false;
					}
				} else {
					notifyNoMorePages();
				}
				
			}
		};

		requestAPI(page, responseListener);
	}
	
	private void getFirstPage() {
		int page = 1;
		ResponseListener responseListener = new ResponseListener() {
			
			@Override
			public void processResponse(int inintstall) {
				notifyNoMorePages();
			}
			
			@Override
			public void processResponse(String response) {
				if (response != null) {
					ArrayList<EmailEntity> list = ParseJSON.getAllEmailsFromResponse(response);
					if (list != null && list.isEmpty() == false) {
						notifyMayHaveMorePages();
						
						resetList(list);
					} else {
						notifyNoMorePages();
					}
				} else {
					notifyNoMorePages();
				}
			}
		};

		requestAPI(page, responseListener);
	}
	
	public void onItemClick(int position) {
		if (getCount() == 0) return;
		EmailEntity currentItem = getItem(position);
		
		DialogUtility.showDialogEmailDetail(parentFragment.getActivity(), currentItem);
	}

}
